package com.hzw.controller;

import com.hzw.dto.ApiResult;
import com.hzw.bean.User;
import com.hzw.dto.UserInfo;
import com.hzw.service.LoginService;
import com.hzw.service.UserService;
import com.hzw.utils.ObjectUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import static com.hzw.api.Api.CLIENT_ERROR;

/**
 * Created by Administrator on 2019/2/27.
 */

@Controller
@CrossOrigin
@RequestMapping(value = "/login")
public class LoginController {
    @Resource
    private LoginService loginService;

    @Resource
    private UserService userService;

    @RequestMapping(value = "/userLogin",method = RequestMethod.POST)
    @ResponseBody
    public ApiResult userLogin(@RequestBody User user) {
        ApiResult result = new ApiResult();
        if (ObjectUtils.isNullOrEmpty(user)) {
            result.error(CLIENT_ERROR, "用户不能为空");
            return result;
        }

        String userName = user.getUserName();
        String password = user.getPassword();
        int userNameCount = 0;  //用户名标志  0:不存在 1:存在
        int matchCount = 0;     //用户名和密码配对标志 0:不成功 1:成功
        if (ObjectUtils.isNullOrEmpty(userName) || ObjectUtils.isNullOrEmpty(password)) {
            result.error(CLIENT_ERROR, "用户名和密码不能为空");
            return result;
        } else {
            userNameCount = userService.checkExistUserName(userName);
            if (userNameCount == 0) {
                result.error(CLIENT_ERROR, "用户名不存在");
                return result;
            }
            matchCount = userService.checkPassword(user);
            if (matchCount == 0) {
                result.error(CLIENT_ERROR, "密码错误");
                return result;
            } else if (matchCount == 1) {   //密码正确，生成token，返回用户信息
                User user1 = loginService.getUserByNameAndPass(user);
                UserInfo userInfo = userService.getUserInfo(user1);
                result.setData(userInfo);
            }
        }
        return result;
    }
}
